package ru.ifmo.lab3;

import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.concurrent.Semaphore;

public class Graph {
    private ArrayList<ArrayList<Edge>> edges;

    public Graph(Integer vertexCount) throws IllegalArgumentException {
        if (vertexCount < 0) {
            throw new IllegalArgumentException("Vertex's count must be positive!");
        }
        this.edges = new ArrayList<ArrayList<Edge>>();

        for (int i = 0; i < vertexCount; ++i) {
            edges.add(new ArrayList<Edge>());
        }
    }

    public void addEdge(Integer vertexTo, Integer vertexFrom, Integer capacity) throws IndexOutOfBoundsException {
        ArrayList<Edge> currentRow = edges.get(vertexTo);
        currentRow.add(new Edge(vertexFrom, capacity));
    }

    public ArrayList<Edge> getAdjEdges(int vertex) throws IndexOutOfBoundsException {
        return edges.get(vertex);
    }

    public ArrayList<Integer> getAdjVertexes(int vertex) throws IndexOutOfBoundsException {
        ArrayList<Integer> vertexes = new ArrayList<Integer>();
        ArrayList<Edge> adjEdges = getAdjEdges(vertex);

        for (Edge edge : adjEdges) {
            vertexes.add(edge.getVertexTo());
        }

        return vertexes;
    }

    public Semaphore getEdgeSemaphore(int vertexFrom, int vertexTo) throws IndexOutOfBoundsException, NoSuchElementException {
        ArrayList<Edge> adjEdges = getAdjEdges(vertexFrom);
        for (Edge edge : adjEdges) {
            if (edge.getVertexTo() == vertexTo) {
                return edge.getSemaphore();
            }
        }
        throw new NoSuchElementException("There are no such adj. vertex!");
    }
}
